
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>

extern void debugLog(const char* _text)
{
    NSLog(@"%s", _text);
}

extern const char* getFilePath(const char* fileName)
{
    NSString *file = [NSString stringWithUTF8String:fileName];
    NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:file];
    
    return (const char*) [path UTF8String];
}


int getPowerOfTwo(int _iValue)
{
	if((_iValue != 1) && (_iValue & (_iValue - 1))) 
	{
		int i = 1;
		while(i < _iValue) i *= 2;
		_iValue = i;
	}
	return _iValue;
}

extern int wrLoadTexture( const char* name, int *_width, int *_height )
{
	NSString *file = [NSString stringWithUTF8String:name];
    NSString *path = [[NSBundle mainBundle] pathForResource:file ofType:@"png"];
    NSData *texData = [[NSData alloc] initWithContentsOfFile:path];
    UIImage *image = [[UIImage alloc] initWithData:texData];

    if (image == nil)
    {
        [image release];
        [texData release];
   
		return -1;
    }
	
	GLuint texture_id[1];
	glGenTextures(1, &texture_id[0]);
	glBindTexture(GL_TEXTURE_2D, texture_id[0]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    GLuint iWidth = CGImageGetWidth(image.CGImage);
    GLuint iHeight = CGImageGetHeight(image.CGImage);
    GLuint width = getPowerOfTwo( iWidth );
    GLuint height = getPowerOfTwo( iHeight );
	*_width = width;
	*_height = height;
	
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    void *imageData = malloc( height * width * 4 );
    CGContextRef context = CGBitmapContextCreate( imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );
    CGColorSpaceRelease( colorSpace );
    CGContextClearRect( context, CGRectMake( 0, 0, width, height ) );
    
    //CGContextSetGrayFillColor(context, 1.0, 0.3);
    //CGContextFillRect(context, CGRectMake(0, 0, width, height));

    CGContextTranslateCTM( context, 0, height - height );
    CGContextDrawImage( context, CGRectMake( (width - iWidth) / 2, (height - iHeight) / 2, iWidth, iHeight ), image.CGImage );

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);

    CGContextRelease(context);

    free(imageData);
    [image release];
    [texData release];
	
	return texture_id[0];
}

extern void wrDeleteTextTexture(int _iTextureID)
{
    GLuint iTextureID = _iTextureID;
    glDeleteTextures(1, &iTextureID);
}

extern int wrCreateTextTexture(const char *str, const char *fontName, float fontSize, int _iHAlign, int _iVAlign, int *_iWidth, int *_iHeight, int *_iTextWidth, int *_iTextHeight, bool _bBreakLines, int _iLineWidth)
{
	UIFont *font = [UIFont fontWithName:[NSString stringWithUTF8String:fontName] size:fontSize];
	
    CGSize size;
    if(_bBreakLines)
    {
        CGSize textMaxSize = CGSizeMake(_iLineWidth, 512);
        size = [[NSString stringWithUTF8String:str] sizeWithFont:font constrainedToSize:textMaxSize lineBreakMode:UILineBreakModeWordWrap];
    }
    else 
    {
        size = [[NSString stringWithUTF8String:str] sizeWithFont:font];
    }
    *_iTextWidth = size.width;
    *_iTextHeight = size.height;
    
	int width = getPowerOfTwo(size.width);
	int height = getPowerOfTwo(size.height);
	
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
	char* data = calloc(height, width);
	CGContextRef context = CGBitmapContextCreate(data, width, height, 8, width, colorSpace, kCGImageAlphaNone);
	CGColorSpaceRelease(colorSpace);
	
	//CGContextSetGrayFillColor(context, 1.0, 0.3);
    //CGContextFillRect(context, CGRectMake(0, 0, width, height));
	CGContextSetGrayFillColor(context, 1.0, 1.0);
    
	CGContextTranslateCTM(context, 0.0, height);
    float fVertDisp = 0;
    if(_iVAlign == 1)
        fVertDisp = (height - size.height) / 2;
    else if(_iVAlign == 2)
        fVertDisp = height - size.height;

	CGContextScaleCTM(context, 1.0, -1.0); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential

	UIGraphicsPushContext(context);

    float fHorDisp = 0;
    if(_iHAlign == 1)
        fHorDisp = (width - size.width) / 2;
    else if(_iHAlign == 2)
        fHorDisp = width - size.width;
    
	[[NSString stringWithUTF8String:str] drawInRect:CGRectMake(fHorDisp, fVertDisp, size.width, size.height) withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:_iHAlign];
	UIGraphicsPopContext();
	CGContextRelease(context);
	
	// Use OpenGL ES to generate a name for the texture.
	GLuint texture_id[1];
	glGenTextures(1, &texture_id[0]);
	glBindTexture(GL_TEXTURE_2D, texture_id[0]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data);

	// Release  the image data; it's no longer needed
	free(data);
	
    *_iWidth = width;
    *_iHeight = height;
    
	return texture_id[0];
}
